package com.kedacom.ctsp.authz.security.provider;

import com.alibaba.fastjson.JSONObject;
import com.kedacom.ctsp.authz.entity.AuthUser;
import com.kedacom.ctsp.authz.exception.UnauthorizedException;
import com.kedacom.ctsp.authz.security.captcha.CaptchaService;
import com.kedacom.ctsp.authz.security.util.AccessLoggerConstant;
import com.kedacom.ctsp.logging.AccessLogger;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 登录成功后自定义处理
 *
 * @author sunchenjie
 * @date 2017-12-07
 */
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired(required = false)
    private CaptchaService captchaService;
    @Value("${server.session.timeout:86400}")
    private int expireTime;
    @Autowired
    private TokenManager tokenManager;

    @AccessLogger(value = AccessLoggerConstant.Module.LOGIN_SUCCESS, describe = AccessLoggerConstant.Module.LOGIN_SUCCESS)
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        HttpSession session = request.getSession(true);
        session.setMaxInactiveInterval(expireTime);
        // 清空登录失败次数
        if (captchaService != null) {
            captchaService.clearLoginWrongTimes(request.getSession());
        }

        com.kedacom.ctsp.authz.entity.Authentication userAuthentication
                = com.kedacom.ctsp.authz.entity.Authentication.current().orElseThrow(UnauthorizedException::new);

        AuthUser authUser = userAuthentication.getUser();

        // 保存token
        Object authObj = request.getAttribute("authUser");
        if (authObj instanceof UserBean) {
            UserBean userBean = (UserBean) authObj;
            if (StringUtils.isNotBlank(userBean.getAccessToken())) {
                authUser = tokenManager.loginDirectly(userBean.getUsername(), userBean.getAccessToken());
            }
        }

        // 返回值
        ResponseMessage<AuthUser> ok = ResponseMessage.ok(authUser);
        response.getWriter().println(JSONObject.toJSON(ok));
    }
}